from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import inspect
from config import mysql_database
from database.database import Base

# 数据库配置
DATABASE_URL = f"mysql+pymysql://{mysql_database['user']}:{mysql_database['password']}@{mysql_database['host']}/{mysql_database['database']}?charset=utf8mb4"

# 全局变量定义
engine = None
SessionLocal = None


# 初始化数据库连接和检查表是否存在
def init_database():
    """初始化数据库连接并检查数据库表是否存在，如果不存在则报错"""
    global engine, SessionLocal
    
    try:
        # 创建数据库引擎
        engine = create_engine(
            DATABASE_URL,
            pool_pre_ping=True,  # 自动检测断开的连接
            connect_args={
                'charset': 'utf8mb4',
                'use_unicode': True
            }
        )
        
        # 测试数据库连接
        with engine.connect() as conn:
            print("数据库连接成功")
            
        # 创建会话工厂
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        # 检查表是否已存在
        inspector = inspect(engine)
        existing_tables = inspector.get_table_names()
        
        # 获取所有模型类的表名
        model_tables = [Base.metadata.tables[table_name].name for table_name in Base.metadata.tables]
        
        # 检查哪些表不存在
        missing_tables = []
        for table_name in model_tables:
            if table_name not in existing_tables:
                missing_tables.append(table_name)
        
        if missing_tables:
            error_msg = f"数据库中缺少必要的表: {', '.join(missing_tables)}。请先创建数据库表。"
            print(error_msg)
            raise Exception(error_msg)
        else:
            print("数据库已经初始化")
            
    except Exception as e:
        print(f"数据库初始化失败: {e}")
        raise


# 数据库依赖
def get_db():
    """获取数据库会话"""
    if SessionLocal is None:
        # 如果SessionLocal未初始化，先初始化数据库
        init_database()
        
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
